<template>
  <view class="browse-container">
    <!-- 状态栏 -->
    <view class="status-bar">
      
    </view>
    
    <!-- 标题栏 -->
    <view class="header">
      <view class="back-button" @click="goBack">
        <image src="/static/arrow-left.png" mode="aspectFit" class="back-icon"></image>
      </view>
      <text class="title">浏览页</text>
      <view class="placeholder"></view>
    </view>
    
    <!-- 搜索栏 -->
    <view class="search-bar">
      <view class="search-input">
        <image class="search-icon" src="/static/search.png" mode="aspectFit"></image>
        <input type="text" v-model="searchKeyword" placeholder="搜索商品" placeholder-class="placeholder" />
      </view>
    </view>
    
    <!-- 筛选条件 -->
    <view class="filter-tabs" v-if="false">
      <view class="filter-item" :class="{ 'active': activeFilter === 'category' }" @click="toggleFilter('category')">
        <text>综合</text>
        <text class="arrow" :class="{ 'arrow-up': activeFilter === 'category' }">▼</text>
      </view>
      <view class="filter-item" :class="{ 'active': activeFilter === 'price' }" @click="toggleFilter('price')">
        <text>价格</text>
        <text class="arrow" :class="{ 'arrow-up': activeFilter === 'price' }">▼</text>
      </view>
      <view class="filter-item" :class="{ 'active': activeFilter === 'newest' }" @click="toggleFilter('newest')">
        <text>上新</text>
        <text class="arrow" :class="{ 'arrow-up': activeFilter === 'newest' }">▼</text>
      </view>
      <view class="filter-item" :class="{ 'active': activeFilter === 'featured' }" @click="toggleFilter('featured')" v-if="false">
        <text>筛选</text>
        <text class="arrow" :class="{ 'arrow-up': activeFilter === 'featured' }">▼</text>
      </view>
    </view>
    
    <!-- 筛选弹出层 - 京东风格 -->
    <view class="jd-filter-mask" v-if="activeFilter !== ''" @click.stop>
      <!-- 价格筛选 -->
      <view class="jd-filter-panel" v-if="activeFilter === 'price'">
        <view class="jd-filter-header">
          <text class="jd-filter-title">价格区间</text>
        </view>
        <view class="jd-filter-content">
          <view class="jd-price-grid">
            <view class="jd-price-item" 
                  v-for="(range, index) in priceRanges" 
                  :key="index"
                  :class="{ 'jd-selected': selectedPriceRange === index }"
                  @click="selectPriceRange(index)">
              <text>{{ range.label }}</text>
            </view>
          </view>
        </view>
        <view class="jd-filter-footer">
          <button class="jd-reset-btn" @click="resetPriceFilter">重置</button>
          <button class="jd-confirm-btn" @click="applyPriceFilter">确定</button>
        </view>
      </view>
      
      <!-- 上新筛选 -->
      <view class="jd-filter-panel" v-if="activeFilter === 'newest'">
        <view class="jd-filter-header">
          <text class="jd-filter-title">商品上新</text>
        </view>
        <view class="jd-filter-content">
          <view class="jd-option-list">
            <view class="jd-option-item" 
                  :class="{ 'jd-selected': isNewFilter === 0 }"
                  @click="isNewFilter = 0">
              <text>上新商品</text>
              <image v-if="isNewFilter === 0" class="jd-check-icon" src="/static/check.png" mode="aspectFit"></image>
            </view>
            <view class="jd-option-item" 
                  :class="{ 'jd-selected': isNewFilter === null }"
                  @click="isNewFilter = null">
              <text>全部商品</text>
              <image v-if="isNewFilter === null" class="jd-check-icon" src="/static/check.png" mode="aspectFit"></image>
            </view>
          </view>
        </view>
        <view class="jd-filter-footer">
          <button class="jd-reset-btn" @click="resetNewFilter">重置</button>
          <button class="jd-confirm-btn" @click="applyNewFilter">确定</button>
        </view>
      </view>
      
      <!-- 综合筛选 -->
      <view class="jd-filter-panel" v-if="activeFilter === 'category'">
        <view class="jd-filter-header">
          <text class="jd-filter-title">综合排序</text>
        </view>
        <view class="jd-filter-content">
          <view class="jd-option-list">
            <view class="jd-option-item" 
                  :class="{ 'jd-selected': sortOption === null }"
                  @click="sortOption = null">
              <text>默认排序</text>
              <image v-if="sortOption === null" class="jd-check-icon" src="/static/check.png" mode="aspectFit"></image>
            </view>
            <view class="jd-option-item" 
                  :class="{ 'jd-selected': sortOption === 0 }"
                  @click="sortOption = 0">
              <text>价格从低到高</text>
              <image v-if="sortOption === 0" class="jd-check-icon" src="/static/check.png" mode="aspectFit"></image>
            </view>
            <view class="jd-option-item" 
                  :class="{ 'jd-selected': sortOption === 1 }"
                  @click="sortOption = 1">
              <text>价格从高到低</text>
              <image v-if="sortOption === 1" class="jd-check-icon" src="/static/check.png" mode="aspectFit"></image>
            </view>
          </view>
        </view>
        <view class="jd-filter-footer">
          <button class="jd-reset-btn" @click="resetCategoryFilter">重置</button>
          <button class="jd-confirm-btn" @click="applyCategoryFilter">确定</button>
        </view>
      </view>
      
      <!-- 筛选 -->
      <view class="jd-filter-panel jd-advanced-filter" v-if="activeFilter === 'featured'">
        <view class="jd-filter-header">
          <text class="jd-filter-title">高级筛选</text>
        </view>
        <view class="jd-filter-content">
          <view class="jd-filter-section">
            <view class="jd-section-title">价格区间</view>
            <view class="jd-price-grid">
              <view class="jd-price-item" 
                    v-for="(range, index) in priceRanges" 
                    :key="index"
                    :class="{ 'jd-selected': selectedPriceRange === index }"
                    @click="selectPriceRange(index)">
                <text>{{ range.label }}</text>
              </view>
            </view>
          </view>
          
          <view class="jd-filter-section">
            <view class="jd-section-title">商品排序</view>
            <view class="jd-option-list">
              <view class="jd-option-item" 
                    :class="{ 'jd-selected': sortOption === 0 }"
                    @click="sortOption = 0">
                <text>价格从低到高</text>
                <image v-if="sortOption === 0" class="jd-check-icon" src="/static/check.png" mode="aspectFit"></image>
              </view>
              <view class="jd-option-item" 
                    :class="{ 'jd-selected': sortOption === 1 }"
                    @click="sortOption = 1">
                <text>价格从高到低</text>
                <image v-if="sortOption === 1" class="jd-check-icon" src="/static/check.png" mode="aspectFit"></image>
              </view>
            </view>
          </view>
          
          <view class="jd-filter-section">
            <view class="jd-section-title">商品上新</view>
            <view class="jd-option-list">
              <view class="jd-option-item" 
                    :class="{ 'jd-selected': isNewFilter === 0 }"
                    @click="isNewFilter = 0">
                <text>上新商品</text>
                <image v-if="isNewFilter === 0" class="jd-check-icon" src="/static/check.png" mode="aspectFit"></image>
              </view>
              <view class="jd-option-item" 
                    :class="{ 'jd-selected': isNewFilter === null }"
                    @click="isNewFilter = null">
                <text>全部商品</text>
                <image v-if="isNewFilter === null" class="jd-check-icon" src="/static/check.png" mode="aspectFit"></image>
              </view>
            </view>
          </view>
        </view>
        <view class="jd-filter-footer">
          <button class="jd-reset-btn" @click="resetAllFilters">重置</button>
          <button class="jd-confirm-btn" @click="applyAllFilters">确定</button>
        </view>
      </view>
    </view>
    
    <!-- 商品列表 -->
    <scroll-view scroll-y class="product-list">
      <view v-if="loading" class="loading">
        <text>加载中...</text>
      </view>
      <view v-else-if="error" class="error">
        <text>{{ error }}</text>
      </view>
      <view v-else-if="products.length === 0" class="empty-state">
        <image src="/static/empty-data.png" mode="aspectFit" class="empty-image"></image>
        <text class="empty-text">暂无商品数据</text>
      </view>
      <view v-else class="product-row">
        <view class="product-card" v-for="(product, index) in products" :key="index" @click="goToProductDetail(product.id)">
          <view class="product-image-container">
            <image class="product-image" :src="product.image" mode="aspectFill"></image>
          </view>
          <view class="product-info">
            <view class="product-title">{{ product.name }}</view>
            <view class="price-action-row">
              <view class="price-row">
                <text class="price-symbol">¥</text>
                <text class="current-price">{{ product.price }}</text>
                <text class="original-price" v-if="product.originalPrice">¥{{ product.originalPrice }}</text>
              </view>
              <view class="cart-button" @click.stop="goToTaobao(product.taocode)" v-if="product.taocode">
                <image src="/static/cart-icon.png" mode="aspectFit"></image>
              </view>
            </view>
          </view>
        </view>
      </view>
    </scroll-view>
    
    <!-- 底部占位 -->
    <view class="bottom-space"></view>
  </view>
</template>

<script>
import { filterProducts } from '../../api/products.js';

export default {
  data() {
    return {
      searchKeyword: '',
      activeFilter: '',
      products: [],
      loading: false,
      error: null,
      // 新增筛选相关数据
      priceRanges: [
        { label: '全部', value: null },
        { label: '¥0-100', value: '0-100' },
        { label: '¥100-300', value: '100-300' },
        { label: '¥300-500', value: '300-500' },
        { label: '¥500-1000', value: '500-1000' },
        { label: '¥1000-1500', value: '1000-1500' },
        { label: '¥1500-2000', value: '1500-2000' },
        { label: '¥2000-2500', value: '2000-2500' },
        { label: '¥2500-3000', value: '2500-3000' },
        { label: '¥3000以上', value: '>3000' }
      ],
      selectedPriceRange: 0,
      isNewFilter: null,
      sortOption: null,
      filterParams: {}
    };
  },
  onLoad(options) {
    // 获取选择页面传递的筛选条件
    const apiParams = uni.getStorageSync('apiParams') || {};
    this.filterParams = { ...apiParams };
    
    // 初始化筛选条件
    if (apiParams.priceAfterTags) {
      const priceIndex = this.priceRanges.findIndex(item => item.value === apiParams.priceAfterTags);
      if (priceIndex !== -1) {
        this.selectedPriceRange = priceIndex;
      }
    }
    
    if (apiParams.isNew !== undefined) {
      this.isNewFilter = parseInt(apiParams.isNew);
    }
    
    if (apiParams.sort !== undefined) {
      this.sortOption = parseInt(apiParams.sort);
    }
    
    this.fetchProducts(this.filterParams);
  },
  methods: {
    goBack() {
      uni.navigateBack();
    },
    goToProductDetail(productId) {
      uni.navigateTo({
        url: `/pages/product-detail/product-detail?id=${productId}`
      });
    },
    toggleFilter(type) {
      this.activeFilter = this.activeFilter === type ? '' : type;
    },
    // 价格范围筛选
    selectPriceRange(index) {
      this.selectedPriceRange = index;
    },
    resetPriceFilter() {
      this.selectedPriceRange = 0;
      this.activeFilter = ''; // 关闭筛选面板
    },
    applyPriceFilter() {
      const selectedRange = this.priceRanges[this.selectedPriceRange];
      if (selectedRange.value) {
        this.filterParams.priceAfterTags = selectedRange.value;
      } else {
        delete this.filterParams.priceAfterTags;
      }
      this.activeFilter = ''; // 关闭筛选面板
      this.fetchProducts(this.filterParams);
    },
    // 上新筛选
    resetNewFilter() {
      this.isNewFilter = null;
      this.activeFilter = ''; // 关闭筛选面板
    },
    applyNewFilter() {
      if (this.isNewFilter !== null) {
        this.filterParams.isNew = this.isNewFilter;
      } else {
        delete this.filterParams.isNew;
      }
      this.activeFilter = ''; // 关闭筛选面板
      this.fetchProducts(this.filterParams);
    },
    // 综合筛选
    resetCategoryFilter() {
      // 重置所有筛选条件
      this.filterParams = {};
      this.selectedPriceRange = 0;
      this.isNewFilter = null;
      this.sortOption = null;
      this.activeFilter = ''; // 关闭筛选面板
    },
    applyCategoryFilter() {
      this.activeFilter = ''; // 关闭筛选面板
      this.fetchProducts(this.filterParams);
    },
    // 价格排序筛选
    resetSortFilter() {
      this.sortOption = null;
      delete this.filterParams.sort;
      this.activeFilter = ''; // 关闭筛选面板
    },
    applySortFilter() {
      if (this.sortOption !== null) {
        this.filterParams.sort = this.sortOption;
      } else {
        delete this.filterParams.sort;
      }
      this.activeFilter = ''; // 关闭筛选面板
      this.fetchProducts(this.filterParams);
    },
    // 重置所有筛选条件
    resetAllFilters() {
      this.filterParams = {};
      this.selectedPriceRange = 0;
      this.isNewFilter = null;
      this.sortOption = null;
      this.activeFilter = ''; // 关闭筛选面板
      this.fetchProducts(this.filterParams); // 添加这行来刷新商品列表
    },
    // 应用所有筛选条件
    applyAllFilters() {
      // 价格筛选
      const selectedRange = this.priceRanges[this.selectedPriceRange];
      if (selectedRange.value) {
        this.filterParams.priceAfterTags = selectedRange.value;
      } else {
        delete this.filterParams.priceAfterTags;
      }
      
      // 上新筛选
      if (this.isNewFilter !== null) {
        this.filterParams.isNew = this.isNewFilter;
      } else {
        delete this.filterParams.isNew;
      }
      
      // 排序筛选
      if (this.sortOption !== null) {
        this.filterParams.sort = this.sortOption;
      } else {
        delete this.filterParams.sort;
      }
      
      this.activeFilter = ''; // 关闭筛选面板
      this.fetchProducts(this.filterParams);
    },
    async fetchProducts(params) {
      try {
        this.loading = true;
        this.error = null;
        console.log('开始获取商品列表，筛选条件：', params);
        
        if (!params) {
          params = {};
        }
        
        const response = await filterProducts(params);
        console.log('接口返回数据：', response);
        
        if (response) {
          this.products = response.data;
          
          // 如果有排序参数，在前端进行排序
          if (params.sort !== undefined) {
            this.products = this.products.sort((a, b) => {
              if (params.sort === 0) {
                // 价格从低到高
                return a.price - b.price;
              } else {
                // 价格从高到低
                return b.price - a.price;
              }
            });
          } else {
            // 默认随机排序
            this.products = this.products;
          }
          
          if (!this.products || this.products.length === 0) {
            this.error = '暂无符合条件的商品';
          }
        } 
      } catch (err) {
        this.error = '网络请求失败，请稍后重试';
        console.error('获取商品列表失败:', err);
      } finally {
        this.loading = false;
      }
    },
    goToTaobao(taocode) {
      // 示例淘宝口令，实际使用时应该从后端获取
      const tbCommand = taocode
      uni.setClipboardData({
        data: tbCommand,
        success: () => {
          uni.showModal({
            title: '淘宝口令已复制',
            content: '请打开淘宝APP查看商品详情',
            showCancel: false,
            confirmText: '我知道了'
          })
        }
      })
    }
  }
};
</script>

<style lang="scss">
.browse-container {
  min-height: 100vh;
  background-color: #f8f8f8;
  display: flex;
  flex-direction: column;
}

.status-bar {
  height: 88rpx;
  padding: 0 32rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #ffffff;
  
  .time {
    font-size: 32rpx;
    font-weight: bold;
    color: #000000;
  }
  
  .right-icons {
    display: flex;
    align-items: center;
    
    .signal, .wifi, .battery {
      background-color: #000000;
      margin-left: 12rpx;
    }
    
    .signal {
      width: 36rpx;
      height: 24rpx;
    }
    
    .wifi {
      width: 32rpx;
      height: 24rpx;
    }
    
    .battery {
      width: 48rpx;
      height: 24rpx;
      border-radius: 6rpx;
    }
  }
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 32rpx;
  background-color: #ffffff;
  
  .back-button {
    width: 60rpx;
    height: 60rpx;
    display: flex;
    align-items: center;
    .back-icon {
      width: 32rpx;
      height: 32rpx;
    }
  }
  .title {
    font-size: 36rpx;
    font-weight: 500;
    color: #000000;
    flex: 1;
    text-align: center;
  }
  .placeholder {
    width: 60rpx;
  }
}
.search-bar {
  padding: 20rpx 32rpx;
  background-color: #ffffff;
  .search-input {
    display: flex;
    align-items: center;
    height: 72rpx;
    background-color: #f5f5f5;
    border-radius: 36rpx;
    padding: 0 30rpx;
    .search-icon {
      width: 32rpx;
      height: 32rpx;
      margin-right: 16rpx;
    }
    input {
      flex: 1;
      height: 100%;
      font-size: 28rpx;
    }
    .placeholder {
      color: #999999;
    }
  }
}
.filter-tabs {
  display: flex;
  height: 80rpx;
  background-color: #fff;
  border-bottom: 1rpx solid #f2f2f2;
}

.filter-item {
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 28rpx;
  color: #333;
  position: relative;
  
  &.active {
    color: #e93b3d;
    font-weight: 500;
    
    &::after {
      content: '';
      position: absolute;
      bottom: 0;
      left: 50%;
      transform: translateX(-50%);
      width: 40rpx;
      height: 4rpx;
      background-color: #e93b3d;
    }
  }
  
  .arrow {
    font-size: 20rpx;
    margin-left: 6rpx;
    transition: transform 0.3s;
  }
  
  .arrow-up {
    transform: rotate(180deg);
  }
}

.jd-filter-mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 999;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.jd-filter-panel {
  position: absolute;
  top: 180rpx;
  left: 0;
  right: 0;
  background-color: #ffffff;
  border-radius: 20rpx 20rpx 0 0;
  z-index: 1000;
  display: flex;
  flex-direction: column;
  max-height: 70vh;
}

.jd-advanced-filter {
  max-height: 80vh;
  overflow-y: auto;
}

.jd-filter-header {
  padding: 30rpx;
  border-bottom: 1rpx solid #f2f2f2;
}

.jd-filter-title {
  font-size: 32rpx;
  font-weight: 500;
  color: #333;
}

.jd-filter-content {
  padding: 20rpx 30rpx;
  max-height: calc(70vh - 200rpx);
  overflow-y: auto;
}

.jd-filter-section {
  margin-bottom: 40rpx;
}

.jd-section-title {
  font-size: 28rpx;
  color: #666;
  margin-bottom: 20rpx;
}

.jd-price-grid {
  display: flex;
  flex-wrap: wrap;
}

.jd-price-item {
  width: 30%;
  height: 70rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f7f7f7;
  border-radius: 35rpx;
  margin: 10rpx;
  font-size: 26rpx;
  color: #333;
  
  &.jd-selected {
    background-color: #f1f8ff;
    color: #2196f3;
    border: 1rpx solid #2196f3;
  }
}

.jd-option-list {
  background-color: #fff;
}

.jd-option-item {
  height: 90rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20rpx;
  border-bottom: 1rpx solid #f7f7f7;
  font-size: 28rpx;
  color: #333;
  
  &.jd-selected {
    color: #e93b3d;
  }
}

.jd-check-icon {
  width: 40rpx;
  height: 40rpx;
}

.jd-filter-footer {
  display: flex;
  padding: 20rpx 30rpx;
  border-top: 1rpx solid #f2f2f2;
}

.jd-reset-btn, .jd-confirm-btn {
  flex: 1;
  height: 80rpx;
  border-radius: 40rpx;
  font-size: 28rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  margin: 0 10rpx;
}

.jd-reset-btn {
  background-color: #f7f7f7;
  color: #666;
}

.jd-confirm-btn {
  background-color: #e93b3d;
  color: #fff;
}

.product-list {
  padding: 20rpx;
  height: calc(100vh - 300rpx);
  box-sizing: border-box;
}

.product-row {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20rpx;
}

.product-card {
  background: #fff;
  border-radius: 16rpx;
  overflow: hidden;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
}

.product-image-container {
  width: 100%;
  padding-top: 100%;
  position: relative;
}

.product-image {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.product-info {
  padding: 16rpx;
}

.product-title {
  font-size: 28rpx;
  color: #333;
  margin-bottom: 12rpx;
  line-height: 1.4;
  height: 80rpx;
  overflow: hidden;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
}

.price-action-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.price-row {
  display: flex;
  align-items: baseline;
}

.price-symbol {
  font-size: 24rpx;
  color: #881B20;
}

.current-price {
  font-size: 32rpx;
  font-weight: bold;
  color: #881B20;
  margin-right: 8rpx;
}

.original-price {
  font-size: 24rpx;
  color: #999;
  text-decoration: line-through;
}

.cart-button {
  width: 48rpx;
  height: 48rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.cart-button image {
  width: 40rpx;
  height: 40rpx;
}

.loading {
  text-align: center;
  padding: 30rpx;
  color: #999;
}

.error {
  text-align: center;
  padding: 30rpx;
  color: #ff4444;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 0;
}

.empty-image {
  width: 240rpx;
  height: 240rpx;
  margin-bottom: 20rpx;
}

.empty-text {
  font-size: 28rpx;
  color: #999;
}
</style>
